<template>
<div>

    <Modal
      v-model="showModal"
      title="添加图片"
      :width="modalWidth"
      :closable ="false"
      @on-visible-change="onVisibleChange"
      footer-hide
      :mask-closable="false"
    >
      <div class="select-imgs" v-if="!stepCropper">
        <Tabs :animated="false" v-model="activeTab">
          <TabPane name="images" label="图片库">
            <div class="iai-add-image__picture-center">
              <div class="iai-add-image__picture-sidebar">
                <Menu
                  theme="light"
                  width="140rpx"
                  :active-name="selectSort"
                  v-if="sorts.length"
                  @on-select="sortChange"
                >
                  <MenuGroup title="我的图片">
                    <MenuItem
                      :name="sort.id"
                      v-for="sort in sorts"
                      :key="sort.id"
                    >{{sort.category_name}}</MenuItem>
                  </MenuGroup>
                </Menu>
              </div>
              <div class="iai-add-image__picture-main">
                <div class="iai-add-image__picture-pagination">
                  <Page :current="currentPage" :total="pickerImgsTotal" :page-size="20" simple @on-change="onPageChange"/>
                </div>
                <div class="ice-any-picker">
                  <div
                    class="ice-any-picker__trigger"
                    v-for="(img, i) in pickerImgs"
                    :key="img.key"
                  >
                    <div
                      class="ice-any-picker__trigger-btn"
                      :class="[
                        { 'ice-any-picker__trigger-btn-checked': img.checked }
                      ]"
                      :data-i="i"
                      :data-src="img.img_url"
                      :data-key="img.key"
                      @click="onPickerTriggerChecked"
                    >
                      <Icon type="md-checkmark" />
                    </div>
                    <div
                      v-if="img.img_width < minWidth || img.img_height < minHeight"
                      class="ice-any-picker__trigger-btn ice-any-picker__trigger-btn-unavailable"
                    >
                      <span>尺寸不符</span>
                    </div>
                    <div class="iai-add-image__resource-pic">
                      <div class="iai-add-image__resource-pic__cover">
                        <img :src="img.img_url" draggable="false" />
                      </div>
                      <div class="iai-add-image__resource-pic__title">{{ img.name }}</div>
                      <div class="iai-add-image__resource-pic__pix">{{ img.img_width }} x {{ img.img_height }}</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </TabPane>
          <TabPane name="upload" label="上传新图片">
            <ui-uploader
              :max-length="lastLen"
              :upload-header="uploadHeader"
              :multiple="mode === 'checkbox'"
              :sorts="uploadSorts"
              @on-success="handleSuccess"
              @on-add-imgurl="handleAddImage"
            />
          </TabPane>
        </Tabs>
        <div class="iai-add-image__selectbar" v-if="pickerSelectesImgs.length">
          <div class="iai-add-image__list">
            <div
              class="iai-add-image__selectbar-item"
              v-for="(img, i) in pickerSelectesImgs"
              :key="img.key"
            >
              <div class="iai-add-image__selectbar-item-cover">
                <img :src="img.img_url" draggable="false" />
              </div>
              <div
                class="iai-add-image__delete"
                :data-i="i"
                :data-key="img.key"
                @click="onRmSelectItem"
              >
                <Icon type="ios-close" />
              </div>
            </div>
          </div>
          
        </div>
        <div class="ice-add-image-dialog-new__footer">
          <div class="ice-add-image-dialog-new__footer__limit"></div>
          <div class="ice-add-image-dialog-new__footer__operation">
            <Button type="primary" @click="onSubmit" :disabled="!pickerSelectesImgs.length">确定</Button>
            <Button @click="onHide">取消</Button>
          </div>
        </div>
      </div>
      <div v-if="stepCropper && needCrop">
        <ui-cropper
          :images="pickerSelectesImgs"
          :CropType="CropType"
          @on-export="onCropperExport"
          @on-visible-change="onVisibleChange"
          :minCropBoxWidth="minWidth"
          :minCropBoxHeight="minHeight"
        />
      </div><Spin size="large" fix v-if="spinShow"></Spin>
    </Modal>

</div>
</template>

<script>
import { getList as getCategoryList } from '@/api/resource/category'
import { getList as getPictureList, store} from '@/api/resource/picture'

import util from '@/libs/util'
import UiCropper from './UiCropper.vue'
import UiUploader from './UiUploader.vue'
export default {
  name: 'ui-add-image',
  components: {
    UiCropper,
    UiUploader
  },
  props: {
    show: Boolean,
    needCrop: Boolean,
    images: {
      type: Array,
      default() {
        return []
      }
    },
    CropType: {
      type: String,
      default() {
        return '11'
      }
    },
    maxLength: {
      type: Number,
      default: 9
    },
    mode: {
      type: String,
      default: 'radio'
    },
    minWidth: {
      type: Number,
      default: 0
    },
    minHeight: {
      type: Number,
      default: 0
    },
  },
  watch: {
    show(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.showModal = newVal
      }
    }
  },
  data() {
    return {
      spinShow:true,
      activeTab: 'images',
      modalWidth: '984px',
      currentPage: 1,
      pickerImgs: [],
      pickerImgsTotal: 0,
      pickerSelectesImgs: [],
      stepCropper: false,
      showModal: false,
      selectedKeys: [],
      sorts: [],
      selectSort: '0',
      page: 1,
      limit: 10,
      count: 0,
      uploadHeader: {},
      uploadSorts: []
    }
  },
  computed: {
    lastLen() {
      const selectedLen = this.pickerSelectesImgs.length
      return this.maxLength - selectedLen
    }
  },
  methods: {
    onReset() {
      this.activeTab = 'images'
      this.selectSort = '0'
      this.stepCropper = false
      this.modalWidth = '984px'
      this.currentPage = 1
      this.pickerImgs = []
      this.pickerImgsTotal = 0
      this.pickerSelectesImgs = []
      this.uploadData = {}
    },
    onRmSelectItem(e) {
      const { key } = e.currentTarget.dataset
      this.pickerSelectesImgs = this.pickerSelectesImgs.filter(
        item => item.key !== key
      )
      
      this.pickerImgs = this.pickerImgs.map(item => {
        return {
          ...item,
          checked: item.key === key ? false : item.checked
        }
      })
    },
    getImages(page) {
      this.spinShow=true
      getPictureList({ cid: this.selectSort, page: page, limit: this.limit }).then(res => {
        this.spinShow=false
        const { count, list } = res.data
        this.pickerImgsTotal = count
        this.pickerImgs = list.map(item => {
          return {
            ...item,
            name: item.title,
            key: `${item.id}`,
            checked: this.pickerSelectesImgs.some(img => Number(item.id) === Number(img.key))
          }
        })
      })
    },
    pageChange (index) {
      this.page = index
      this.getImages()
    },
    sortChange(id) {
      this.selectSort = id
      this.getImages(1)
    },
    onVisibleChange(res) {
      if (res) {
        this.onReset()
        getCategoryList({ category_type: 1 }).then(res => {
          const { data } = res
          this.sorts = data
          this.uploadSorts = data
            .filter(item => Number(item.id) !== 0)
            .map(item => ({
              ...item,
              id: Number(item.id)
            }))
        })
        this.getImages(1)
      } else {
        // do something
        this.onHide()
      }
    },
    onPickerTriggerChecked(e) {
      const { i, key } = e.currentTarget.dataset
      const cur = this.pickerImgs.filter(item => item.key === key)[0]
      const selfChecked = cur.checked
      if (!this.lastLen && !selfChecked) {
        this.$Message['error']({
          background: true,
          content: '最多可添加'+this.maxLength+'张种草图片'
        })
        return
      }
      if (this.mode === 'checkbox') {
        this.$set(this.pickerImgs, i, {
          ...cur,
          checked: !selfChecked
        })
        if (selfChecked) {
          this.pickerSelectesImgs = this.pickerSelectesImgs.filter(
            item => item.key !== key
          )
          this.selectedKeys = this.selectedKeys.filter(item => item !== key)
        } else {
          this.pickerSelectesImgs = [...this.pickerSelectesImgs, cur]
          this.selectedKeys = [...this.selectedKeys, key]
        }
      } else {
        this.pickerSelectesImgs = selfChecked ? [] : [cur]
        this.selectedKeys = selfChecked ? [] : [key]
        this.pickerImgs = this.pickerImgs.map(item => {
          let checked = item.checked
          if (item.key === key) {
            if (selfChecked) {
              checked = false
            } else {
              checked = true
            }
          } else {
            checked = false
          }
          return {
            ...item,
            checked
          }
        })
      }
    },
    onSubmit() {
      if (this.needCrop) {
        this.modalWidth = '472px'
        this.stepCropper = true
      } else {
        this.$emit('on-export', {
          images: this.pickerSelectesImgs
        })
        this.onHide()
      }
    },
    handleSuccess({res, file, cid}) {
      if(res.status !== 200) {
        this.$Message.warning({
            content: JSON.stringify(res.msg),
            duration: 6
        });
        return
      }

      const { data } = res
      const { name } = file
      store({
        cid,
        title: name,
        img_url: data.img_url,
        img_width: data.img_width,
        img_height: data.img_height,
      }).then(({ msg }) => {
        if (this.mode === 'checkbox') {
          this.pickerSelectesImgs.push({
            name,
            img_url: data.img_url,
            key: msg,
            checked: true
          })
        } else {
          this.pickerSelectesImgs = [
            {
              name,
              img_url: data.img_url,
              key: msg,
              checked: true
            }
          ]
        }
      })
    },
    // 添加图片
    handleAddImage(row) {
      this.pickerSelectesImgs = [
        {
          name: 'image',
          img_url: row.img_url,
          key: 1,
          checked: true
        }
      ]
    },
    onCropperExport(res) {
      this.$emit('on-export', res)
      this.onHide()
    },
    onHide() {
      this.$emit('on-visible-change', false)
    },
    onPageChange(i) {
      this.getImages(i)
    }
  },
  mounted() {
    this.uploadHeader['Authori-zation'] = 'Bearer ' + util.cookies.get('token')
  }
}
</script>
<style lang="scss">
.iai-add-image__picture-sidebar {
  width: 140px;
  flex: 0 0 140px;
  overflow-y: auto;
  .ivu-menu-item-group-title {
    padding-left: 12px;
  }
}
.ice-add-image-dialog-new__footer__operation {
  display: flex;
  .ivu-btn {
    & + .ivu-btn {
      margin-left: 8px;
    }
  }
}
</style>
<style lang="scss" scoped>
.iai-add-image__picture-center {
  display: flex;
  height: 460px;
  border: 1px solid #e7e7e7;
}
.iai-add-image__picture-sidebar {
  width: 140px;
  flex: 0 0 140px;
  overflow-y: auto;
  .ivu-menu {
    height: 100%;
  }
}
.iai-add-image__picture-main {
  flex: 1;
}
.iai-add-image__picture-pagination {
  display: flex;
  justify-content: flex-end;
  padding: 12px 0;
}
.ice-any-picker {
  height: 410px;
  overflow-y: auto;
  display: flex;
  flex-wrap: wrap;
}
.ice-any-picker__trigger {
  margin-left: 12px;
  padding-bottom: 12px;
  position: relative;
}
.iai-add-image__resource-pic {
  width: 145px;
  height: 190px;
  border: 1px solid #e7e7e7;
}
.iai-add-image__resource-pic__cover {
  height: 143px;
  width: 143px;
  overflow: hidden;
  img {
    max-width: 100%;
    max-height: 100%;
    opacity: 1;
    vertical-align: middle;
  }
}
.iai-add-image__resource-pic__title {
  font-size: 12px;
  color: #999;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  padding: 0 10px;
  line-height: 20px;
  padding-top: 5px;
}
.iai-add-image__resource-pic__pix {
  font-size: 12px;
  color: #999;
  padding: 0 10px;
  line-height: 20px;
}
.ice-any-picker__trigger-btn {
  width: 143px;
  height: 143px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  top: 0;
  left: 0;
  cursor: pointer;
  text-align: center;
  color: #fff;
  .ivu-icon {
    font-size: 28px;
    font-weight: bold;
    visibility: hidden;
  }
}
.ice-any-picker__trigger-btn-checked {
  background-color: rgba(#000, 0.5);
  .ivu-icon {
    visibility: visible;
  }
}

.ice-any-picker__trigger-btn-unavailable {
  width: 143px;
  height: 143px;
  line-height: 143px;
  background-color: rgba(255,255,255,.7);
  cursor: not-allowed;
  span{
    font-size: 18px;
    color: #666;
  }
}
</style>
